package com.example.driptip;

import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import android.content.Context;
import android.widget.ImageButton;
import android.widget.Button;
import android.widget.TextView;

import com.example.driptip.databinding.ActivityMainBinding;
import com.example.driptip.ui.home.HomeFragment;
import com.example.driptip.model.Checklist;
import com.example.driptip.util.ChecklistManager;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
    private AlertDialog currentAlertDialog;
    private final ActivityResultLauncher<Intent> overlayPermissionLauncher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        result -> {
            if (Settings.canDrawOverlays(this)) {
                if (currentAlertDialog != null && currentAlertDialog.isShowing()) {
                    currentAlertDialog.dismiss();
                }
            } else {
            }
        }
    );

    private ChecklistManager checklistManager;
    private Checklist checklist;
    private boolean isChecklistEnabled = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);

            binding = ActivityMainBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());

            setSupportActionBar(binding.appBarMain.toolbar);

            // Load HomeFragment
            if (savedInstanceState == null) {
                getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_container, new HomeFragment())
                    .commit();
            }

            // 初始化清单管理器
            checklistManager = new ChecklistManager(this);
            checklist = checklistManager.loadChecklist();

        } catch (Exception e) {
            Toast.makeText(this, "App startup failed: " + e.getMessage(), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        MenuItem checkboxItem = menu.findItem(R.id.action_checkbox);
        checkboxItem.setChecked(isChecklistEnabled);
        checkboxItem.setIcon(isChecklistEnabled ? R.drawable.ic_checkbox_on : R.drawable.ic_checkbox_off);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_checkbox) {
            isChecklistEnabled = !isChecklistEnabled;
            item.setChecked(isChecklistEnabled);
            item.setIcon(isChecklistEnabled ? R.drawable.ic_checkbox_on : R.drawable.ic_checkbox_off);
            return true;
        } else if (id == R.id.action_checklist) {
            showChecklistDialog();
            return true;
        } else if (id == R.id.action_settings) {
            showHomeSettings();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showHomeSettings() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_home_settings, null);
            
        // Get switch controls
        androidx.appcompat.widget.SwitchCompat popupSwitch = dialogView.findViewById(R.id.switch_popup);
        androidx.appcompat.widget.SwitchCompat smsSoundSwitch = dialogView.findViewById(R.id.switch_sms_sound);
        androidx.appcompat.widget.SwitchCompat vibrationSwitch = dialogView.findViewById(R.id.switch_vibration);
        ImageView warningIcon = dialogView.findViewById(R.id.iv_warning);

        // Check overlay permission
        boolean hasOverlayPermission = Settings.canDrawOverlays(this);
        popupSwitch.setEnabled(hasOverlayPermission);
        popupSwitch.setChecked(hasOverlayPermission);
        warningIcon.setVisibility(hasOverlayPermission ? View.GONE : View.VISIBLE);

        // 根据权限隐藏或显示权限说明
        TextView tvPermissionExplanation = dialogView.findViewById(R.id.tv_permission_explanation);
        tvPermissionExplanation.setVisibility(hasOverlayPermission ? View.GONE : View.VISIBLE);

        // Set warning icon click handler
        warningIcon.setOnClickListener(v -> {
            try {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(android.net.Uri.parse("package:" + getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                overlayPermissionLauncher.launch(intent);
            } catch (Exception e) {
                Toast.makeText(this, "Cannot open permission settings: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        // Load settings from SharedPreferences
        android.content.SharedPreferences prefs = getSharedPreferences("home_settings", MODE_PRIVATE);
        if (hasOverlayPermission) {
            popupSwitch.setChecked(prefs.getBoolean("popup_enabled", false));
        }
        smsSoundSwitch.setChecked(prefs.getBoolean("sms_sound_enabled", true));
        vibrationSwitch.setChecked(prefs.getBoolean("vibration_enabled", true));

        // Create dialog
        currentAlertDialog = new AlertDialog.Builder(this)
            .setView(dialogView)
            .setPositiveButton("应用", null)
            .setNegativeButton("取消", null)
            .create();

        // Show dialog
        currentAlertDialog.show();

        // Override positive button click
        currentAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
            // Save settings to SharedPreferences
            android.content.SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("popup_enabled", popupSwitch.isChecked());
            editor.putBoolean("sms_sound_enabled", smsSoundSwitch.isChecked());
            editor.putBoolean("vibration_enabled", vibrationSwitch.isChecked());
            editor.apply();

            // Close dialog
            currentAlertDialog.dismiss();
        });
    }

    private void showChecklistDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_checklist, null);
        builder.setView(dialogView);

        // 获取所有EditText和按钮
        EditText[] editTexts = new EditText[10];
        ImageButton[] copyButtons = new ImageButton[10];
        ImageButton[] removeButtons = new ImageButton[10];
        ImageButton[] pasteButtons = new ImageButton[10];

        // 检查闹钟是否在运行
        final boolean isAlarmRunning;
        HomeFragment homeFragment = (HomeFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container);
        if (homeFragment != null) {
            isAlarmRunning = homeFragment.isAlarmRunning();
        } else {
            isAlarmRunning = false;
        }

        for (int i = 0; i < 10; i++) {
            View itemView = dialogView.findViewById(getResources().getIdentifier("item_" + (i + 1), "id", getPackageName()));
            editTexts[i] = itemView.findViewById(R.id.edit_checklist);
            copyButtons[i] = itemView.findViewById(R.id.btn_copy_item);
            removeButtons[i] = itemView.findViewById(R.id.btn_remove_item);
            pasteButtons[i] = itemView.findViewById(R.id.btn_paste_item);

            editTexts[i].setText(checklist.getItem(i));

            // 如果闹钟在运行，禁用编辑和删除、粘贴，复制按钮始终可用
            if (isAlarmRunning) {
                editTexts[i].setEnabled(false);
                removeButtons[i].setEnabled(false);
                pasteButtons[i].setEnabled(false);
                copyButtons[i].setEnabled(true); // 复制按钮始终可用
            } else {
                editTexts[i].setEnabled(true);
                removeButtons[i].setEnabled(true);
                pasteButtons[i].setEnabled(true);
                copyButtons[i].setEnabled(true);
            }

            // 设置焦点变化监听器
            editTexts[i].setOnFocusChangeListener((v, hasFocus) -> {
                if (!hasFocus) {
                    // 当失去焦点时保存所有内容
                    for (int j = 0; j < 10; j++) {
                        checklist.setItem(j, editTexts[j].getText().toString());
                    }
                    checklistManager.saveChecklist(checklist);
                }
            });

            // 设置复制按钮点击事件
            final int index = i;
            copyButtons[i].setOnClickListener(v -> {
                String text = editTexts[index].getText().toString();
                if (!text.isEmpty()) {
                    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    android.content.ClipData clip = android.content.ClipData.newPlainText("清单项", text);
                    clipboard.setPrimaryClip(clip);
                    Toast.makeText(this, "已复制", Toast.LENGTH_SHORT).show();
                }
            });

            // 设置删除按钮点击事件
            removeButtons[i].setOnClickListener(v -> {
                if (!isAlarmRunning) {
                    editTexts[index].setText("");
                    // 将后面的项向前移动
                    for (int j = index; j < 9; j++) {
                        editTexts[j].setText(editTexts[j + 1].getText().toString());
                    }
                    editTexts[9].setText("");
                }
            });

            // 设置粘贴按钮点击事件
            pasteButtons[i].setOnClickListener(v -> {
                if (!isAlarmRunning) {
                    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    if (clipboard.hasPrimaryClip() && clipboard.getPrimaryClip().getItemCount() > 0) {
                        String text = clipboard.getPrimaryClip().getItemAt(0).getText().toString();
                        if (!text.isEmpty()) {
                            // 从后向前移动，为当前项腾出空间
                            for (int j = 9; j > index; j--) {
                                editTexts[j].setText(editTexts[j - 1].getText().toString());
                            }
                            // 粘贴内容到当前项
                            editTexts[index].setText(text);
                        }
                    } else {
                        Toast.makeText(this, "剪贴板为空", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

        // 设置顶部按钮点击事件
        Button btnClear = dialogView.findViewById(R.id.btn_clear);
        Button btnCopy = dialogView.findViewById(R.id.btn_copy);
        Button btnPaste = dialogView.findViewById(R.id.btn_paste);

        // 如果闹钟在运行，禁用清空和粘贴，复制按钮始终可用
        if (isAlarmRunning) {
            btnClear.setEnabled(false);
            btnPaste.setEnabled(false);
            btnCopy.setEnabled(true);
        } else {
            btnClear.setEnabled(true);
            btnPaste.setEnabled(true);
            btnCopy.setEnabled(true);
        }

        btnClear.setOnClickListener(v -> {
            if (!isAlarmRunning) {
                for (EditText editText : editTexts) {
                    editText.setText("");
                }
            }
        });

        btnCopy.setOnClickListener(v -> {
            StringBuilder sb = new StringBuilder();
            for (EditText editText : editTexts) {
                String text = editText.getText().toString();
                if (!text.isEmpty()) {
                    sb.append(text).append("\n");
                }
            }
            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            android.content.ClipData clip = android.content.ClipData.newPlainText("清单", sb.toString());
            clipboard.setPrimaryClip(clip);
            Toast.makeText(this, "已复制清单", Toast.LENGTH_SHORT).show();
        });

        btnPaste.setOnClickListener(v -> {
            if (!isAlarmRunning) {
                android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                if (clipboard.hasPrimaryClip() && clipboard.getPrimaryClip().getItemCount() > 0) {
                    String text = clipboard.getPrimaryClip().getItemAt(0).getText().toString();
                    String[] lines = text.split("\n");
                    for (int i = 0; i < Math.min(lines.length, 10); i++) {
                        editTexts[i].setText(lines[i]);
                    }
                }
            }
        });

        builder.setPositiveButton("更新", (dialog, which) -> {
            // 保存所有内容
            for (int i = 0; i < 10; i++) {
                checklist.setItem(i, editTexts[i].getText().toString());
            }
            checklistManager.saveChecklist(checklist);
        });

        builder.setNegativeButton("取消", null);
        builder.show();
    }

    public boolean isChecklistEnabled() {
        return isChecklistEnabled;
    }
}